package com.hk.utils;

import org.springframework.beans.BeanUtils;

import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * 实体Bean工具类
 */
public class BeanUtil {
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    /**
     *
     * @param source
     * @param target
     * @param classObj
     * @param <T>
     */
    public static <T> void copyPropertiesList(Object source, List<T> target, Class<T> classObj) {
        if ((!Objects.isNull(source)) && (!Objects.isNull(target))) {
            List list1 = (List)source;
            list1.forEach(item -> {
                try {
                    T data = classObj.newInstance();
                    BeanUtils.copyProperties(item, data);
                    target.add(data);
                } catch (InstantiationException e) {
                } catch (IllegalAccessException e) {
                }

            });
        }
    }

    /**
     * 深度拷贝
     * 
     * @param src
     * @return
     */
    public static Object deepCopy(Object src) {
        Object dest = null;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            dest = in.readObject();
        } catch (IOException e) {

        } catch (ClassNotFoundException e) {

        }
        return dest;
    }
}
